<template>
  <!-- 首页/商品管理/参数列表 -->
  <div>
    <!--  面包屑导航区  -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item><span>参数列表</span></el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          选择商品分类:
          <!-- 商品分类的级联选择框 -->
          <el-cascader
            v-model="selectCateKeys"
            :props="cateProps"
            :options="cateList"
            expand-Trigger="hover"
            @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <!--   页签区域   -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--   添加动态参数   -->
        <el-tab-pane label="动态参数"  name="many">
          <el-button type="primary" :disabled="isBtnDisable" @click="addDialogVisible = true" size="mini">添加参数</el-button>
          <!--   动态参数表格   -->
          <el-table :data="manyTableData" border stripe>

            <!--   展开行   -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!--  循环渲染tag标签-->
                <el-tag closable @close="removeTag(i, scope.row)" v-for="(item, i) in scope.row.attr_vals" :key="i">
                  {{item}}
                </el-tag>
                <!--  输入得文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--  添加按钮-->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+新建标签</el-button>
              </template>
            </el-table-column>

            <!--   索引列   -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" >
              <template slot-scope="scope" >
                <el-button size="mini" type="primary" @click="showEditDialog(scope.row.attr_id)" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" @click="removeParamById(scope.row.attr_id)" icon="el-icon-delete">删除</el-button>
              </template>

            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--   添加静态属性   -->
        <el-tab-pane label="静态参数" name="only">
          <el-button type="primary" :disabled="isBtnDisable" @click="addDialogVisible = true" size="mini">添加属性</el-button>
          <!--   静态参数   -->
          <el-table :data="onlyTableData" border stripe>
            <!--   展开行   -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!--  循环渲染tag标签-->
                <el-tag closable @close="removeTag(i, scope.row)" v-for="(item, i) in scope.row.attr_vals" :key="i">
                  {{item}}
                </el-tag>
                <!--  输入得文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--  添加按钮-->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+新建标签</el-button>
              </template>
            </el-table-column>
            <!--   索引列   -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditDialog(scope.row.attr_id)" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" @click="removeParamById(scope.row.attr_id)" icon="el-icon-delete">删除</el-button>
              </template>

            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数弹出得对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="500px"
      @close="addDialogClosed">
      <!--  添加属性得表单    -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="auto">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addPrams">确 定</el-button>
  </span>
    </el-dialog>
    <!-- 编辑按钮弹出得对话框 -->

    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamDialogVisible"
      @close="editParamClosed"
      width="500px">
      <el-form ref="editParamFormRef" :model="editParamForm" :rules="addFormRules" label-width="auto">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editParamDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联双向绑定到的数组
      selectCateKeys: [],
      // 被激活的页签名称
      activeName: 'many',
      // 动态得数据
      manyTableData: [],
      // 静态得数据
      onlyTableData: [],
      // 控制弹出得对话框
      addDialogVisible: false,
      // 添加参数表单得数据对象
      addForm: {
        attr_name: ''
      },
      // 添加表单得验证规则对象
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      },
      editParamDialogVisible: false,
      // 修改得表单数据对象
      editParamForm: {}

    };
  },
  created () {
    this.getCateList();
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList () {
      const { data: res } = await axios.get('categories');
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败!');
      this.cateList = res.data;
      console.log(this.cateList);
    },
    // 级联框变化触发的函数
    handleChange () {
      this.getParamsData();
    },

    // Tab页签点击事件处理函数
    handleTabClick () {
      this.getParamsData();
    },
    // 获取动态静态参数得列表数据
    async getParamsData () {
      // 证明选中的不是三级分类
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      // 证明选中的是三级分类
      // 根据所选分类的Id,和当前面板的参数, 获取对应的参数
      const { data: res } = await axios.get(`categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } });

      if (res.meta.status !== 200) {
        this.$message.error('获取参数列表失败!');
      }
      console.log(res.data);
      res.data.forEach(item => {
        //   通过三元表达式判断attr_vals是否为空
        item.attr_vals = item.attr_vals
          ? item.attr_vals.split(' ') : [];
        // 控制文本框得显示与隐藏
        item.inputVisible = false;
        // 文本框中输入得值
        item.inputValue = '';
      });
      console.log(res.data);
      // 动态参数和静态属性要做一个区别
      if (this.activeName === 'many') {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },

    // 监听对话框得关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields();
    },

    // 添加动态参数和静态属性得确定按钮
    addPrams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败!');
        }
        this.$message.success('添加参数成功!');
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },

    // 点击编辑按钮弹出对话框
    async showEditDialog (id) {
      console.log(id);
      this.editParamDialogVisible = true;
      // 根据第三级cateId 查询属性,再根据属性id获取
      const { data: res } = await axios.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } });
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败!');
      }
      this.editParamForm = res.data;
    },
    // 修改参数得提交
    editParams () {
      this.$refs.editParamFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await axios.put(
          `categories/${this.cateId}/attributes/${this.editParamForm.attr_id}`,
          {
            attr_name: this.editParamForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败!');
        }
        this.$message.success('修改参数成功!');
        this.getParamsData();
        this.editParamDialogVisible = false;
      });
    },

    // 根据cateId,attr_id删除参数
    async removeParamById (id) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'error'
        }
      ).catch(err => err);
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      // 删除逻辑
      const { data: res } = await axios.delete(`categories/${this.cateId}/attributes/${id}`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败!');
      }
      this.$message.success('删除参数成功!');
      this.getParamsData();
    },

    // 修改框得关闭
    editParamClosed () {
      this.$refs.editParamFormRef.resetFields();
    },

    // new tag失去焦点或者按下得 enter 被弹起
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = '';
        row.inputVisible = false;
        return this.$message.warning('输入内容无效，请重新输入!');
      }
      // 如果没有return 则证明输入得内容有效  需要做后续处理
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = '';
      row.inputVisible = false;
      this.savaAttrValues(row);
    },

    // 点击了按钮要展示文本输入框
    showInput (row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点 就是让光标在输入框里面
      // $nextTick方法的作用：当页面元素被重新渲染之后，才会至指定回调函数中的代码
      // 为什么要放在这个函数里面呢？ 如果不重新渲染直接调用 可能会找不到输入框
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 点击x 删除标签
    removeTag (i, row) {
      row.attr_vals.splice(i, 1);
      this.savaAttrValues(row);
    },

    // 将对attr_vals（Tag） 的操作 保存到数据库
    async savaAttrValues (row) {
      // 需要发起请求保存这次操作
      const temp = row.attr_vals;
      const { data: res } = await axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          // 之前事通过 split(' ') 字符串转数组，现在把新数组转化成字符串存入数据库
          attr_vals: row.attr_vals.join(' ')
        });
      if (res.meta.status !== 200) {
        return temp.length < row.attr_vals
          ? this.$message.error('添加标签失败!') : this.$message.error('删除标签失败!');
      }
      return temp.length < row.attr_vals
        ? this.$message.success('添加标签成功!') : this.$message.success('删除标签成功!');
    }

  },
  computed: {
    // 如果按钮需要被禁用 返回true
    isBtnDisable () {
      if (this.selectCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中得三级分类id
    cateId () {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2];
      }
      return null;
    },
    // 动态计算弹出框标题
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数';
      }
      return '静态属性';
    }

  }
};
</script>

<style lang="less" scoped>
span{
  font-weight: bold;
  color: #409eff;
}
.cat_opt {
   margin: 20px 0;
}
.el-tag {
  margin: 5px
}
.input-new-tag {
  width: 120px
 }
</style>
